import { resourceLibraryApi } from '@/api';
import { getGovernmentTestPaperDetail } from '@/api/Plan';
import imgLock from '@/img/img_lock.png';
import { useAppSelector } from '@/redux/store';
import { DoubleRightOutlined } from '@ant-design/icons';
import { useSafeState } from 'ahooks';
import { App, Button, Descriptions } from 'antd';
import classNames from 'classnames';
import { useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import TestPaperItem from './TestPaperItem';

function TestPaperDetail(props: {
  coursewareId: string;
  resourceType?: string;
  hasPayService?: boolean;
  isCharge?: number;
}) {
  const navigator = useNavigate();
  const {
    coursewareId,
    resourceType = '200', // '100':企业协会自建 ，'200'：平台
    hasPayService = true, //organizationType === 0 && resourceType === '200' 是否购买安学行服务
    isCharge = 0, //当前资源是否需要付费 1：付费，0：免费
  } = props;
  const { message } = App.useApp();
  const { loginRole } = useAppSelector((state) => state.loginUser);
  const [videCourseWareDetail, setVideCourseWareDetail] = useSafeState<any>();
  useEffect(() => {
    if (resourceType === '200') {
      resourceLibraryApi.getCourseWareById({ coursewareId }).then((res) => {
        const data: any = res.data;
        let questions: any[] = [];
        const { questionsInfo } = data;
        try {
          questions = JSON.parse(questionsInfo);
        } catch (err) {
          console.log('--TestPaperDetail--jsonPareser--questionsInfo--err--:', err);
        }

        const scoreMap = new Map<number, any[]>();
        questions.forEach((queItem: any) => {
          const { type } = queItem;
          if (type === 100) {
            if (!scoreMap.get(100)) {
              scoreMap.set(100, []);
            }
            scoreMap.get(100)!.push(queItem);
          } else if (type === 200) {
            if (!scoreMap.get(200)) {
              scoreMap.set(200, []);
            }
            scoreMap.get(200)!.push(queItem);
          } else if (type === 300) {
            if (!scoreMap.get(300)) {
              scoreMap.set(300, []);
            }
            scoreMap.get(300)!.push(queItem);
          }
        });

        const newShowQuestions: any[] = [];
        for (const [key, value] of scoreMap.entries()) {
          const score = value[0].score;
          let name;
          if (key === 100) {
            name = '单选题';
          } else if (key === 200) {
            name = '多选题';
          } else if (key === 300) {
            name = '判断题';
          }
          newShowQuestions.push({ name, score, questionList: value });
        }
        // console.log('--newShowQuestions--:', newShowQuestions);
        data.newShowQuestions = newShowQuestions;
        setVideCourseWareDetail(data);
      });
    } else {
      //企业协会
      getGovernmentTestPaperDetail(coursewareId).then((res: any) => {
        const data: any = res.data;
        data.newShowQuestions = data.questionTypeList.map((quesItem: any) => {
          let name;
          const { questionType } = quesItem;
          if (questionType === 100) {
            name = '单选题';
          } else if (questionType === 200) {
            name = '多选题';
          } else if (questionType === 300) {
            name = '判断题';
          }
          return {
            ...quesItem,
            name,
          };
        });
        console.log('--data.newShowQuestions--:', data.newShowQuestions);
        setVideCourseWareDetail(data);
      });
    }
  }, []);

  return (
    <div
      className={classNames('courseware_drawer_content', {
        content_test_paper_cannot_see: resourceType === '200' && isCharge && !hasPayService,
      })}
    >
      {videCourseWareDetail && (
        <>
          <Descriptions column={2} className="ym_descriptions">
            <Descriptions.Item label="试卷名称" span={2}>
              {videCourseWareDetail.name}
            </Descriptions.Item>
            <Descriptions.Item label="及格分数" span={2}>
              <span>满分{videCourseWareDetail.totalScore}分，</span>&nbsp;&nbsp;
              <span>{videCourseWareDetail.passScore}分及格</span>
            </Descriptions.Item>
          </Descriptions>
          <Descriptions column={2} className="ym_descriptions">
            <Descriptions.Item label="" span={2}>
              <div style={{ width: '100%' }}>
                {videCourseWareDetail.newShowQuestions.map((paperItem: any, index: number) => (
                  <TestPaperItem
                    key={index}
                    index={index}
                    score={paperItem.score}
                    name={paperItem.name}
                    questions={paperItem.questionList}
                  />
                ))}
              </div>
            </Descriptions.Item>
          </Descriptions>
        </>
      )}
      {resourceType === '200' && isCharge && !hasPayService ? (
        <div className="cannot_see_mask">
          <div className="mask_top"></div>
          <div className="mask_content">
            <img src={imgLock} alt="imgLock" width={100} height={100} />
            <div className="mask-text">
              企业还未购买 <span>安学行学习位</span>，无法查看收费内容，请前往购买 <span>安学行学习位</span>!
            </div>
            <Button
              type="primary"
              size="large"
              shape="round"
              style={{ padding: '0 20px' }}
              onClick={() => {
                if (loginRole == '1' || loginRole == '0') {
                  navigator('/safeService/buyService');
                } else {
                  message.warning('您暂无权限，请联系企业管理人员！');
                }
              }}
            >
              前往购买
              <DoubleRightOutlined />
            </Button>
          </div>
        </div>
      ) : null}
    </div>
  );
}

export default TestPaperDetail;
